﻿using System.Collections.Generic;
using System.Web.Mvc;
using Orchard;
using Orchard.Autoroute.Models;
using Orchard.ContentManagement;
using Orchard.Environment.Extensions;
using Orchard.Localization;
using Orchard.Mvc;
using Orchard.Mvc.Extensions;
using Orchard.Themes;
using OrchardHUN.QnA.Services;
using Contrib.Taxonomies.Models;

namespace OrchardHUN.QnA.Controllers
{
    [Themed]
    [OrchardFeature("OrchardHUN.QnA")]
    public class QnADiscussionsController : Controller, IUpdateModel
    {
        private readonly IOrchardServices _orchardServices;
        private readonly IContentManager _contentManager;
        private readonly IDiscussionsService _discussionService;

        public Localizer T { get; set; }

        public QnADiscussionsController(
            IOrchardServices orchardServices,
            IDiscussionsService discussionService)
        {
            _orchardServices = orchardServices;
            _contentManager = _orchardServices.ContentManager;
            _discussionService = discussionService;

            T = NullLocalizer.Instance;
        }

        public ActionResult NewDiscussion(int discussionPoolId = 0)
        {
            if (discussionPoolId == 0) return null;
            if (!IsAuthorized()) return RedirectToLogOn();

            return NewDiscussionShapeResult(_discussionService.New(discussionPoolId));
        }

        [HttpPost, ActionName("NewDiscussion")]
        public ActionResult NewDiscussionPost()
        {
            if (!IsAuthorized()) return RedirectToLogOn();

            var discussion = _contentManager.New("QnADiscussion");
            
            _contentManager.UpdateEditor(discussion, this);

            if (discussion.As<TermsPart>().Terms == null || discussion.As<TermsPart>().Terms.Count == 0)
            {
                ModelState.AddModelError("Categories", T("You haven't selected any categories."));
            }

            if (ModelState.IsValid)
            {
                _discussionService.Create(discussion);

                // This is for removing unnecessary "Permalinks in conflict." notification if the discussion
                // created has the same title as one before. Not nice, but this is not possible with Placement.info.
                var notifications = _orchardServices.Notifier.List() as IList<Orchard.UI.Notify.NotifyEntry>;
                notifications.Clear();

                return this.RedirectLocal("~/" + discussion.As<AutoroutePart>().Path);
            }

            return NewDiscussionShapeResult(discussion);
        }

        private bool IsAuthorized()
        {
            return _orchardServices.Authorizer.Authorize(Permissions.CreateDiscussion, T("Please log in to create a new discussion"));
        }

        private ActionResult RedirectToLogOn()
        {
            return this.RedirectLocal(
                Url.Action("LogOn",
                    new
                    {
                        Controller = "Account",
                        Area = "Orchard.Users",
                        ReturnUrl = _orchardServices.WorkContext.HttpContext.Request.RawUrl
                    })
                );
        }

        private ShapeResult NewDiscussionShapeResult(IContent discussion)
        {
            dynamic shape = _contentManager.BuildEditor(discussion);

            return new ShapeResult(this,
                _orchardServices.New.NewDiscussion(
                        EditorShape: shape
                    )
                );
        }

        bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties)
        {
            return TryUpdateModel(model, prefix, includeProperties, excludeProperties);
        }

        void IUpdateModel.AddModelError(string key, LocalizedString errorMessage)
        {
            ModelState.AddModelError(key, errorMessage.ToString());
        }
    }
}
